import { defineComponent, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { FormInst, NForm, NFormItem, NInput, NButton, FormRules, NImage, useMessage } from 'naive-ui'

import './index.styl'

interface Form {
  userName: string
  password: string
}

export default defineComponent({
  name: 'AppLogin',
  setup() {
    const router = useRouter()
    const message = useMessage()

    const form = reactive<Form>({
      userName: '',
      password: ''
    })

    const passwordType = ref<'password' | 'text'>('password')

    const formRef = ref<FormInst | null>(null)

    const rules: FormRule<Form> = {
      userName: { required: true, message: '请输入账户' },
      password: { required: true, message: '请输入密码' }
    }

    return {
      form,
      formRef,
      rules,
      passwordType,
      login(e: MouseEvent) {
        e.preventDefault()

        formRef.value?.validate(errors => {
          if (errors) return

          message.success('登录成功')
          router.push('/product/list')
        })
      }
    }
  },
  render() {
    return (
      <section class='login-container'>
        <NForm
          labelWidth={80}
          model={this.form}
          rules={this.rules as FormRules}
          labelPlacement='left'
          ref='formRef'
          class='login-form'>
          <div class='login-form-title'>
            <NImage previewDisabled width={300} />
          </div>

          <NFormItem label='账户' path='userName' style={{ '--n-color': 'transparent' }}>
            <NInput v-model:value={this.form.userName} autofocus placeholder='手机号' />
          </NFormItem>

          <NFormItem label='密码' path='password'>
            <NInput v-model:value={this.form.password} type={this.passwordType} placeholder='密码' />
          </NFormItem>

          <div>
            <NButton
              attrType='submit'
              block
              type='primary'
              bordered={false}
              onClick={this.login}
              class='login-form-submit'>
              登录
            </NButton>
          </div>
        </NForm>
      </section>
    )
  }
})
